#!/bin/bash

# 导入 nginx/ssl 下的 smartinput 证书到系统
# 适用于 macOS 系统

set -e

echo "=== 导入 nginx/ssl 下的 smartinput 证书到系统 ==="

# 检查证书文件
CERT_FILE="ssl/smartinput.crt"
if [ ! -f "$CERT_FILE" ]; then
    echo "❌ 错误: 找不到证书文件 $CERT_FILE"
    exit 1
fi

echo "✅ 找到证书文件: $CERT_FILE"

# 显示证书信息
echo ""
echo "=== 证书信息 ==="
openssl x509 -in "$CERT_FILE" -text -noout | grep -A 10 "Subject Alternative Name"

# 导入证书到登录钥匙串
echo ""
echo "=== 导入证书到登录钥匙串 ==="
echo "导入证书到登录钥匙串..."
security import "$CERT_FILE" -k ~/Library/Keychains/login.keychain-db

if [ $? -eq 0 ]; then
    echo "✅ 证书已成功导入到登录钥匙串"
else
    echo "❌ 证书导入失败"
    exit 1
fi

# 设置证书为信任状态
echo ""
echo "=== 设置证书信任状态 ==="
echo "设置证书为信任状态..."
security add-trusted-cert -d -r trustRoot -k ~/Library/Keychains/login.keychain-db "$CERT_FILE"

if [ $? -eq 0 ]; then
    echo "✅ 证书已设置为信任状态"
else
    echo "❌ 设置证书信任状态失败"
    echo "请手动在钥匙串访问中设置证书为信任状态"
fi

# 导入证书到系统 Keychain
echo ""
echo "=== 导入证书到系统 Keychain ==="
echo "导入证书到系统 Keychain..."
sudo security import "$CERT_FILE" -k /Library/Keychains/System.keychain -T /usr/bin/codesign

if [ $? -eq 0 ]; then
    echo "✅ 证书已成功导入到系统 Keychain"
else
    echo "❌ 证书导入失败"
    echo "这可能需要管理员权限"
fi

# 设置系统证书为信任状态
echo ""
echo "=== 设置系统证书信任状态 ==="
echo "设置系统证书为信任状态..."
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "$CERT_FILE"

if [ $? -eq 0 ]; then
    echo "✅ 系统证书已设置为信任状态"
else
    echo "❌ 设置系统证书信任状态失败"
    echo "请手动在钥匙串访问中设置证书为信任状态"
fi

# 验证证书导入
echo ""
echo "=== 验证证书导入 ==="
echo "检查登录钥匙串中的证书:"
security find-certificate -c "192.168.137.122" ~/Library/Keychains/login.keychain-db

if [ $? -eq 0 ]; then
    echo "✅ 登录钥匙串中找到了证书"
else
    echo "❌ 未在登录钥匙串中找到证书"
fi

echo ""
echo "检查系统钥匙串中的证书:"
security find-certificate -c "192.168.137.122" /Library/Keychains/System.keychain

if [ $? -eq 0 ]; then
    echo "✅ 系统 Keychain 中找到了证书"
else
    echo "❌ 未在系统 Keychain 中找到证书"
fi

# 测试 HTTPS 连接
echo ""
echo "=== 测试 HTTPS 连接 ==="
echo "测试 HTTPS 连接（忽略证书验证）:"
curl -k -I https://192.168.137.122/api/auth/test

echo ""
echo "测试 HTTPS 连接（验证证书）:"
curl -I https://192.168.137.122/api/auth/test

echo ""
echo "=== 证书信任状态检查 ==="
echo "检查证书信任设置:"
security find-trust-settings -d "192.168.137.122" ~/Library/Keychains/login.keychain-db

echo ""
echo "=== 完成 ==="
echo "证书导入和信任设置完成，现在可以："
echo "1. 重启浏览器（Chrome、Safari 等）"
echo "2. 清除浏览器缓存和 SSL 状态"
echo "3. 重新访问 https://192.168.137.122"
echo "4. 如果仍有证书警告，请手动在钥匙串访问中设置信任"
echo ""
echo "手动设置信任的步骤："
echo "1. 打开 '钥匙串访问' 应用"
echo "2. 在左侧选择 '登录' 钥匙串"
echo "3. 搜索 '192.168.137.122'"
echo "4. 双击证书，在 '信任' 部分设置为 '始终信任'"
echo "5. 关闭窗口并保存更改" 